package com.thinkgem.jeesite.modules.lottery.mobile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.thinkgem.jeesite.common.utils.LotteryContractUtils;
import com.thinkgem.jeesite.common.utils.MapListUtils;
import com.thinkgem.jeesite.modules.lottery.entity.*;
import com.thinkgem.jeesite.modules.lottery.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@Controller
@RequestMapping(value = "lottery")
public class ActivityApiController {
    @Autowired
    WechatUserService wechatUserService;
    @Autowired
    ActivityService activityService;
    @Autowired
    PrizeService prizeService;
    @Autowired
    ActivityFormService activityFormService;
    @Autowired
    ActivityStatusService activityStatusService;
    @Autowired
    MapListUtils mapListUtils;
    @Autowired
    private ParticipationService participationService;

    @RequestMapping(value = {"activity"}, method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public @ResponseBody
    String activity(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String,String> requestJson) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> result = new HashMap<>();
        //获取活动列表
        if (requestJson.get("message").equals("getAll")) {
            List<Activity> activityList = activityService.findList(new Activity());
            if(activityList.size()==0){
                result.put("code",1);
                result.put("message","没有进行中的活动");
                return mapper.writeValueAsString(result);
            }
            activityList.forEach(activity -> activity.setDetail(null));
            activityList.forEach(activity -> activity.setExplanation(null));
            activityList.forEach(activity -> activity.setStartTime(null));
            result.put("code", 0);
            result.put("message", "请求成功");
            List<Map<String,Object>> activities = new ArrayList<>();
            for(Activity activity:activityList){
                Map<String,Object> amap = new HashMap<>();
                amap.put("activity_id",activity.getId());
                //获得活动发起人的昵称和头像
                WechatUser creator = wechatUserService.findByOpenid(activity.getOpenid());
                amap.put("nickname",creator.getNickname());
                amap.put("creator_image",creator.getImage());
                amap.put("activity_id",activity.getId());
                amap.put("name",activity.getName());
                amap.put("image",activity.getImage());
                amap.put("end_time",activity.getEndTime());
                //获得prize数组
                Prize prize = new Prize();
                prize.setActivityId(activity.getId());
                List<Prize> prizeList = prizeService.findList(prize);
                prizeList.forEach(prize1 -> prize1.setId(null));
                amap.put("prize",prizeList);
                //获得活动状态与开奖形式
                ActivityForm activityForm = activityFormService.get(activity.getFormId());
                ActivityStatus activityStatus = activityStatusService.get(activity.getStatusId());
                amap.put("form",activityForm.getDescription());
                amap.put("status",activityStatus.getDescription());
                activities.add(amap);
            }
            result.put("data",activities);
            String s = mapper.writeValueAsString(result);
            return s;
        }
        //获取某个活动列表
        else if (requestJson.get("message").equals("getActivityById")){
            String activityId = requestJson.get("activity_id").toString();
            if (activityId==null||activityId.isEmpty()){
                result.put("code",1);
                result.put("message","活动不存在");
                return mapper.writeValueAsString(result);
            }
            Activity activity = activityService.get(activityId);
            if(activity==null){
                result.put("code",1);
                result.put("message","活动不存在");
                return mapper.writeValueAsString(result);
            }
            Map<String,Object> data = new HashMap<>();
            data.put("activity_id",activity.getId());
            //获得活动发起人昵称和头像
            WechatUser creator = wechatUserService.findByOpenid(activity.getOpenid());
            data.put("creator_image",creator.getImage());
            data.put("nickname",creator.getNickname());
            data.put("detail",activity.getDetail());
            data.put("activity_id",activity.getId());
            data.put("name",activity.getName());
            data.put("image",activity.getImage());
            data.put("end_time",activity.getEndTime());
            data.put("explanation",activity.getExplanation());
            data.put("min_num",activity.getMinNum());
            //获得中奖详情
            //获得prize数组
            Prize prize = new Prize();
            prize.setActivityId(activity.getId());
            List<Prize> prizeList = prizeService.findList(prize);
            prizeList.forEach(prize1 -> prize1.setId(null));
            data.put("prize",prizeList);
            //获得活动状态与开奖形式
            ActivityStatus activityStatus = activityStatusService.get(activity.getStatusId());
            ActivityForm activityForm = activityFormService.get(activity.getFormId());
            data.put("form",activityForm.getDescription());
            data.put("status",activityStatus.getDescription());
            /*
            * 注意补全
            * */
            //参与人数
            int count = 0;
            Participation tempp = new Participation();
            tempp.setActivityId(activityId);
            count = participationService.findList(tempp).size();
            data.put("count",count);
            //参与人的头像
            String openid = requestJson.get("openid");
            List<String> heads = participationService.getWechatUserImageOfActivity(activityId);
            data.put("heads",heads);
            //可以参与吗?
            tempp.setOpenid(openid);
            //参与过了，结束了，就不能参与了。
            if(participationService.findList(tempp).size()==0||!activityStatus.getId().equals("0")){
                data.put("joinable",1);
            }
            else {
                data.put("joinable", 0);
            }
            //可以开奖吗？有权限没结束就能开奖
            WechatUser user = new WechatUser();
            user.setId(openid);
            user.setActorId("1");
            //进行中，是发起人
            if(activity.getStatusId().equals("0")&&creator.getOpenid().equals(openid)){
                data.put("runnable",1);
            }
            else {
                data.put("runnable",0);
            }
            //中奖了吗
            data.put("win","0");
            List<Participation> jointemp = participationService.findList(tempp);
            for(Participation p:jointemp){
                if(p!=null&&p.getOpenid().equals(openid)){
                    data.put("win","1");
                    for(Prize ppp:mapListUtils.getPrizes(activityId)){
                        if(p!=null&&p.getPrizeclassId()!=null&&ppp.getId()!=null&&p.getPrizeclassId().equals(ppp.getId())){
                            data.put("winprize",ppp.getName());
                            break;
                        }
                    }
                }
            }
            List<Map<String,Object>> pni=new ArrayList<>();
            //中奖详情
            //获取每一种奖品的
            for(Prize p:prizeList){
                //该种奖品的所有信息map
                Map<String,Object> tempmap = new HashMap<>();
                tempmap.put("name",p.getName());
                tempmap.put("description",p.getDescription());
                tempmap.put("quantity",p.getQuantity());
                //该种奖品中奖用户的信息[nickname,image]
                List<String[]> winUsers = new ArrayList<>();
                Participation part = new Participation();
                part.setPrizeclassId(p.getId());
                List<Participation> thisprizePartList = participationService.findList(part);
                //temppart是遍历的该奖品的参与情况
                for(Participation temppart:thisprizePartList){
                    WechatUser checkuser = new WechatUser();
                    checkuser.setOpenid(temppart.getOpenid());
                    if(wechatUserService.findList(checkuser)!=null){
                        WechatUser tempwe = wechatUserService.findList(checkuser).get(0);
                        String[] tempstring = {tempwe.getNickname(),tempwe.getImage()};
                        winUsers.add(tempstring);
                    }
                }
                tempmap.put("winUsers",winUsers);
                pni.add(tempmap);
            }
            data.put("winners",pni);
            //返回的结果汇总
            result.put("code",0);
            result.put("message","请求成功");
            result.put("data",data);
            return mapper.writeValueAsString(result);
        }
        //参与抽奖
        else if (requestJson.get("message").equals("participate")){
            result.put("code", 0);
            result.put("message", "参与成功");
            String openid = requestJson.get("openid");
            String activityId = requestJson.get("activity_id");
            System.out.println(requestJson.toString());
            Participation participation = new Participation();
            participation.setActivityId(activityId);
            participation.setOpenid(openid);
            participation.setJoinTime(new Date());
            participationService.save(participation);
            LotteryContractUtils.record(activityId,openid);
            return mapper.writeValueAsString(result);
        }
        else if (requestJson.get("message").equals("run")){
            String activityId = requestJson.get("activity_id");
            run(activityId);
            result.put("code", 0);
            result.put("message", "开奖成功");
            return mapper.writeValueAsString(result);
        }
        else if(requestJson.get("message").equals("getWin")){
            List<Activity> activityList = new ArrayList<>();
            Participation checkjoin = new Participation();
            checkjoin.setOpenid(requestJson.get("openid"));
            for(Participation p : participationService.findList(checkjoin)){
                if(p.getPrizeclassId()!=null&&!p.getPrizeclassId().equals("")){
                    Activity tempchecka = new Activity();
                    tempchecka.setId(p.getActivityId());
                    activityList.add(activityService.findList(tempchecka).get(0));
                }
            }
            if(activityList.size()==0){
                result.put("code",1);
                result.put("message","没有进行中的活动");
                return mapper.writeValueAsString(result);
            }
            activityList.forEach(activity -> activity.setDetail(null));
            activityList.forEach(activity -> activity.setExplanation(null));
            activityList.forEach(activity -> activity.setStartTime(null));
            result.put("code", 0);
            result.put("message", "请求成功");
            List<Map<String,Object>> activities = new ArrayList<>();
            for(Activity activity:activityList){
                Map<String,Object> amap = new HashMap<>();
                amap.put("activity_id",activity.getId());
                //获得活动发起人的昵称和头像
                WechatUser creator = wechatUserService.findByOpenid(activity.getOpenid());
                amap.put("nickname",creator.getNickname());
                amap.put("creator_image",creator.getImage());
                amap.put("activity_id",activity.getId());
                amap.put("name",activity.getName());
                amap.put("image",activity.getImage());
                amap.put("end_time",activity.getEndTime());
                //获得prize数组
                Prize prize = new Prize();
                prize.setActivityId(activity.getId());
                List<Prize> prizeList = prizeService.findList(prize);
                prizeList.forEach(prize1 -> prize1.setId(null));
                amap.put("prize",prizeList);
                //获得活动状态与开奖形式
                ActivityForm activityForm = activityFormService.get(activity.getFormId());
                ActivityStatus activityStatus = activityStatusService.get(activity.getStatusId());
                amap.put("form",activityForm.getDescription());
                amap.put("status",activityStatus.getDescription());
                activities.add(amap);
            }
            result.put("data",activities);
            String s = mapper.writeValueAsString(result);
            return s;
        }
        else if(requestJson.get("message").equals("getAdd")){
            Activity checka = new Activity();
            checka.setOpenid(requestJson.get("openid"));
            List<Activity> activityList = activityService.findList(checka);
            if(activityList.size()==0){
                result.put("code",1);
                result.put("message","没有进行中的活动");
                return mapper.writeValueAsString(result);
            }
            activityList.forEach(activity -> activity.setDetail(null));
            activityList.forEach(activity -> activity.setExplanation(null));
            activityList.forEach(activity -> activity.setStartTime(null));
            result.put("code", 0);
            result.put("message", "请求成功");
            List<Map<String,Object>> activities = new ArrayList<>();
            for(Activity activity:activityList){
                Map<String,Object> amap = new HashMap<>();
                amap.put("activity_id",activity.getId());
                //获得活动发起人的昵称和头像
                WechatUser creator = wechatUserService.findByOpenid(activity.getOpenid());
                amap.put("nickname",creator.getNickname());
                amap.put("creator_image",creator.getImage());
                amap.put("activity_id",activity.getId());
                amap.put("name",activity.getName());
                amap.put("image",activity.getImage());
                amap.put("end_time",activity.getEndTime());
                //获得prize数组
                Prize prize = new Prize();
                prize.setActivityId(activity.getId());
                List<Prize> prizeList = prizeService.findList(prize);
                prizeList.forEach(prize1 -> prize1.setId(null));
                amap.put("prize",prizeList);
                //获得活动状态与开奖形式
                ActivityForm activityForm = activityFormService.get(activity.getFormId());
                ActivityStatus activityStatus = activityStatusService.get(activity.getStatusId());
                amap.put("form",activityForm.getDescription());
                amap.put("status",activityStatus.getDescription());
                activities.add(amap);
            }
            result.put("data",activities);
            String s = mapper.writeValueAsString(result);
            return s;
        }
        else if(requestJson.get("message").equals("getJoin")){
            Participation checkp = new Participation();
            checkp.setOpenid(requestJson.get("openid"));
            List<Participation> joinList = participationService.findList(checkp);
            List<Activity> activityList = new ArrayList<>();
            for(Participation j:joinList){
                Activity tempact = new Activity();
                tempact.setId(j.getActivityId());
                activityList.add(activityService.findList(tempact).get(0));
            }
            if(activityList.size()==0){
                result.put("code",1);
                result.put("message","没有进行中的活动");
                return mapper.writeValueAsString(result);
            }
            activityList.forEach(activity -> activity.setDetail(null));
            activityList.forEach(activity -> activity.setExplanation(null));
            activityList.forEach(activity -> activity.setStartTime(null));
            result.put("code", 0);
            result.put("message", "请求成功");
            List<Map<String,Object>> activities = new ArrayList<>();
            for(Activity activity:activityList){
                Map<String,Object> amap = new HashMap<>();
                amap.put("activity_id",activity.getId());
                //获得活动发起人的昵称和头像
                WechatUser creator = wechatUserService.findByOpenid(activity.getOpenid());
                amap.put("nickname",creator.getNickname());
                amap.put("creator_image",creator.getImage());
                amap.put("activity_id",activity.getId());
                amap.put("name",activity.getName());
                amap.put("image",activity.getImage());
                amap.put("end_time",activity.getEndTime());
                //获得prize数组
                Prize prize = new Prize();
                prize.setActivityId(activity.getId());
                List<Prize> prizeList = prizeService.findList(prize);
                prizeList.forEach(prize1 -> prize1.setId(null));
                amap.put("prize",prizeList);
                //获得活动状态与开奖形式
                ActivityForm activityForm = activityFormService.get(activity.getFormId());
                ActivityStatus activityStatus = activityStatusService.get(activity.getStatusId());
                amap.put("form",activityForm.getDescription());
                amap.put("status",activityStatus.getDescription());
                activities.add(amap);
            }
            result.put("data",activities);
            String s = mapper.writeValueAsString(result);
            return s;
        }
        else {
            result.put("code", 1);
            result.put("message", "????");
            return mapper.writeValueAsString(result);
        }

    }
    @RequestMapping(value = {"addActivity"}, method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public @ResponseBody
    String addActivity(HttpServletRequest request, HttpServletResponse response, @RequestBody String jsonString)throws Exception{
        JSONObject requestJson = JSON.parseObject(jsonString, JSONObject.class);
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> result = new HashMap<>();

        //添加活动
        if(requestJson.getString("message").equals("addActivity")){
            System.out.println("添加添加");
            String creatorid = requestJson.getString("openid");
            System.out.println("creatorid = "+creatorid);
            WechatUser creator = wechatUserService.findByOpenid(creatorid);
            if(mapListUtils.getMangers().contains(creator)){
                JSONObject data = requestJson.getJSONObject("data");
                String openid = creatorid;
                String name = data.getString("name");
                String image = data.getString("image");
                String detail = data.getString("detail");
                String end_time = data.getString("end_time");
                Integer min_num = data.getInteger("min_num");
                String explanation = data.getString("explanation");
                String form = data.getString("form");
                JSONArray prizes = data.getJSONArray("prize");
                Activity activity=new Activity();
                activity.setStartTime(new Date());
                activity.setStatusId("0");
                activity.setOpenid(openid);
                activity.setImage(image);
                activity.setName(name);
                activity.setDetail(detail);
                if(end_time!=null&&!end_time.isEmpty()){
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    activity.setEndTime(df.parse(end_time));
                }
                activity.setMinNum(min_num);
                if(form.equals("手动开奖")){
                    activity.setFormId("1");
                }
                else if (form.equals("自动开奖")){
                    activity.setFormId("0");
                }
                activity.setExplanation(explanation);
                activityService.save(activity);
                System.out.println(activity.toString());
                for (int i=0;i<prizes.size();i++){
                    JSONObject prize = prizes.getJSONObject(i);
                    String description = prize.getString("description");
                    String prizename = prize.getString("name");
                    Integer quantity = prize.getInteger("quantity");
                    Integer sort = prize.getInteger("sort");
                    Prize p = new Prize();
                    p.setDescription(description);
                    p.setName(prizename);
                    p.setQuantity(quantity);
                    p.setSort(sort);
                    p.setActivityId(activity.getId());
                    prizeService.save(p);
                }
                result.put("code", 0);
                result.put("message", "添加成功");
                return mapper.writeValueAsString(result);
            }
            else{
                result.put("code", 1);
                result.put("message", "无发起权限");
                return mapper.writeValueAsString(result);
            }
        }
        result.put("code",0);
        result.put("message","添加成功");
        return mapper.writeValueAsString(result);
    }

    private List<Integer> getRand(int quantity,int range){
        List<Integer> winners = new ArrayList<>();
        Random random = new Random();
        int i = 0;
        while(i<quantity){
            Integer temp = random.nextInt(range);
            if(!winners.contains(temp)){
                winners.add(temp);
                i++;
            }
        }
        return winners;
    }
    private boolean run(String activityId){
        Activity activity = new Activity();
        activity.setId(activityId);
        List<Activity> activities = activityService.findList(activity);
        System.out.println(activities.toString());
        if(activities!=null){
            Activity activity1=activities.get(0);
            for(Activity a:activities){
                activity1 = a;
                break;
            }
            if(!activity1.getStatusId().equals("0")) return false;
            //找该活动的所有prize
            Prize prize = new Prize();
            prize.setActivityId(activityId);
            List<Prize> prizes = prizeService.findList(prize);
            if(prizes==null) return false;
            Integer prizeSum = 0;
            for(Prize p:prizes){
                prizeSum+=p.getQuantity();
            }
            //找参与总人数
            int joinSum = participationService.getNumOfWechatUser(activityId);
            List<Integer> winnerIndex = getRand(prizeSum,joinSum);
            //分奖，也就是把在参与表的prizeid字段加字
            //先找到参与的所有人
            Participation participation = new Participation();
            participation.setActivityId(activityId);
            List<Participation> all = participationService.findList(participation);
            int index = 0;
            for(Prize p:prizes){
                for(int i=0;i<p.getQuantity();i++){
                    Participation temp = all.get(winnerIndex.get(index++));
                    temp.setPrizeclassId(p.getId());
                    participationService.save(temp);
                    System.out.println(temp.toString());
                    System.out.println(p.toString());
                }
            }
            activity1.setStatusId("1");
            activityService.save(activity1);
            return true;
        }
        else{
            return false;
        }
    }
}
